package com.study.test2;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClasspathScanner {

    public static void main(String[] args) throws Exception {
        Class<?> interfaceClass = Class.forName("com.example.MyInterface");
        List<Class<?>> implementingClasses = findImplementations(interfaceClass);

        for (Class<?> clazz : implementingClasses) {
            System.out.println("找到实现类: " + clazz.getName());
        }
    }

    public static List<Class<?>> findImplementations(Class<?> interfaceClass) throws IOException, ClassNotFoundException {
        List<Class<?>> implementations = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = interfaceClass.getPackage().getName().replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }

        for (File directory : dirs) {
            implementations.addAll(findClasses(directory, interfaceClass.getPackage().getName(), interfaceClass));
        }

        return implementations;
    }

    private static List<Class<?>> findClasses(File directory, String packageName, Class<?> interfaceClass) throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }

        File[] files = directory.listFiles();
        if (files == null) {
            return classes;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                classes.addAll(findClasses(file, packageName + "." + file.getName(), interfaceClass));
            } else if (file.getName().endsWith(".class")) {
                Class<?> clazz = Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6));
                if (interfaceClass.isAssignableFrom(clazz) && !clazz.isInterface()) {
                    classes.add(clazz);
                }
            }
        }
        return classes;
    }
}
